package com.wengen.mybatis.session;

import com.wengen.mybatis.config.Configuration;
import com.wengen.mybatis.config.MappedStatement;
import com.wengen.mybatis.excutor.DefaultExcutor;
import com.wengen.mybatis.excutor.Excutor;
import com.wengen.mybatis.proxy.MapperProxy;

import java.lang.reflect.Proxy;
import java.util.List;

/**
 * @Auther: 朱稳根
 * @Date: 2018/8/27 22:17
 * @Description:
 * 1.对外提供查询接口，并把查询请求转发给excutor
 * 2.
 */
public class DefaultSqlSession implements  SqlSession{
    private Configuration conf;

    private Excutor excutor;

    public DefaultSqlSession(Configuration conf) {

        this.conf = conf;
        this.excutor = new DefaultExcutor(conf);
    }

    @Override
    public <T> T selectOne(String statement, Object parameter) {
        List<Object> selelctList = this.selectList(statement, parameter);
        if (selelctList == null || selelctList.size() == 0) {
            return null;
        }
        if(selelctList.size()==1){
            return (T) selelctList.get(0);
        }else{
            throw new RuntimeException("too many result-----");
        }

    }

    @Override
    public <E> List<E> selectList(String statement, Object paramenter) {
        MappedStatement ms = conf.getMapStatements().get(statement);
        return excutor.query(ms, paramenter);
    }

    @Override
    public <T> T getMapper(Class<T> type) {
        MapperProxy mp = new MapperProxy(this);
        return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class[]{type}, mp);
    }
}
